package com.example.interfaces.exchange_confirm_02;

import com.example.mq.MyCallBack;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.PostConstruct;
import java.util.UUID;

/**
 * ClassName: MessageProduct
 * author: bob.ly
 * Version: 1.0.0
 * DateTime: 2021/07/26-22:35:00
 * Description:
 */
@Slf4j
@RequestMapping("/test")
@RestController
public class MessageProduct {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MyCallBack myCallBack;

    /**
     * rabbitMq注入之后就设置该值
     * true:交换机无法将消息路由时, 将消息返回给生产者
     * false: 直接丢弃
     * 设置回退消息交给谁处理
     */
    @PostConstruct
    private void init() {
        rabbitTemplate.setConfirmCallback(myCallBack);
        rabbitTemplate.setMandatory(true);
        rabbitTemplate.setReturnsCallback(myCallBack);
    }

    @GetMapping("sendMessage/{message}")
    public void sendMessage(@PathVariable("message") String message) {
        //让消息绑定一个 id 值
        CorrelationData correlationData1 = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("confirm.exchange", "key1", message + "key1", correlationData1)
        ;
        log.info("发送消息 id 为:{},内容为{}", correlationData1.getId(), message + "key1");
        CorrelationData correlationData2 = new CorrelationData(UUID.randomUUID().toString());
        rabbitTemplate.convertAndSend("confirm.exchange", "key2", message + "key2", correlationData2)
        ;
        log.info("发送消息 id 为:{},内容为{}", correlationData2.getId(), message + "key2");
    }
}
